package it.sportingnola.soccernotes.adapter;

import it.sportingnola.soccernotes.DbHelper;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.widget.ArrayAdapter;
import android.widget.Filter;

/**
 * Questa classe controlla i suggerimenti per i campi relativi alle squadre
 * 
 * @author paolo
 */
public class TeamACAdapter extends ArrayAdapter<String> {

    private class TeamFilter extends Filter {

	@Override
	protected FilterResults performFiltering(CharSequence constraint) {
	    FilterResults results=new FilterResults();
	    // in caso di costraint vuoto restituisci una lista vuota
	    if ((constraint == null) || (constraint.length() == 0)) {
		synchronized (mLock) {
		    ArrayList<String> list=new ArrayList<String>();
		    results.values=list;
		    results.count=list.size();
		}
	    }
	    else {
		String constr=constraint.toString();
		mObjects=helper.cercaVecchieSquadre(constr);
		results.values=mObjects;
		results.count=mObjects.size();
	    }
	    return results;
	}

	@Override
	protected void publishResults(CharSequence constraint, FilterResults results) {
	    if (results.count > 0) {
		notifyDataSetChanged();
	    }
	    else {
		notifyDataSetInvalidated();
	    }
	}
    }

    private List<String> mObjects;
    private final Object mLock=new Object();

    private final DbHelper helper;

    private TeamFilter mFilter;

    public TeamACAdapter(Context context, int textViewResourceId, DbHelper dbHelper) {
	super(context, textViewResourceId);
	helper=dbHelper;
    }

    @Override
    public int getCount() {
	if (mObjects == null) {
	    return 0;
	}
	return mObjects.size();
    }

    @Override
    public Filter getFilter() {
	if (mFilter == null) {
	    mFilter=new TeamFilter();
	}
	return mFilter;
    }

    @Override
    public String getItem(int position) {
	if (mObjects == null) {
	    return null;
	}
	return mObjects.get(position);
    }

    @Override
    public int getPosition(String item) {
	if (mObjects == null) {
	    return - 1;
	}
	return mObjects.indexOf(item);
    }

}
